import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { Notification } from '@/types/notification';
import { notificationApi } from '@/lib/api';

interface NotificationState {
  // 通知列表
  notifications: Notification[];
  // 未读通知数量
  unreadCount: number;
  // 是否正在加载
  isLoading: boolean;
  // 错误信息
  error: string | null;
  // 获取通知列表
  fetchNotifications: () => Promise<void>;
  // 标记通知为已读
  markAsRead: (notificationId: string) => Promise<void>;
  // 标记所有通知为已读
  markAllAsRead: () => Promise<void>;
  // 删除通知
  deleteNotification: (notificationId: string) => Promise<void>;
  // 添加新通知（通常由WebSocket触发）
  addNotification: (notification: Notification) => void;
  // 重置状态
  reset: () => void;
}

export const useNotificationStore = create<NotificationState>()(
  devtools(
    persist(
      (set, get) => ({
        notifications: [],
        unreadCount: 0,
        isLoading: false,
        error: null,

        // 获取通知列表
        fetchNotifications: async () => {
          set({ isLoading: true, error: null });

          try {
            const response = await notificationApi.getNotifications();
            const unreadCount = response.filter((n: Notification) => !n.read).length;
            
            set({
              notifications: response,
              unreadCount,
              isLoading: false,
            });
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '获取通知失败',
              isLoading: false,
            });
          }
        },

        // 标记通知为已读
        markAsRead: async (notificationId: string) => {
          try {
            await notificationApi.markAsRead(notificationId);
            
            set((state) => {
              const updatedNotifications = state.notifications.map((notification) =>
                notification.id === notificationId
                  ? { ...notification, read: true }
                  : notification
              );
              
              return {
                notifications: updatedNotifications,
                unreadCount: state.unreadCount > 0 ? state.unreadCount - 1 : 0,
              };
            });
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '标记通知失败',
            });
          }
        },

        // 标记所有通知为已读
        markAllAsRead: async () => {
          try {
            await notificationApi.markAllAsRead();
            
            set((state) => ({
              notifications: state.notifications.map((notification) => ({
                ...notification,
                read: true,
              })),
              unreadCount: 0,
            }));
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '标记所有通知失败',
            });
          }
        },

        // 删除通知
        deleteNotification: async (notificationId: string) => {
          try {
            await notificationApi.deleteNotification(notificationId);
            
            set((state) => {
              const notification = state.notifications.find(
                (n) => n.id === notificationId
              );
              
              const unreadCount = notification && !notification.read
                ? state.unreadCount - 1
                : state.unreadCount;
              
              return {
                notifications: state.notifications.filter(
                  (n) => n.id !== notificationId
                ),
                unreadCount: unreadCount < 0 ? 0 : unreadCount,
              };
            });
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '删除通知失败',
            });
          }
        },

        // 添加新通知
        addNotification: (notification: Notification) => {
          set((state) => ({
            notifications: [notification, ...state.notifications],
            unreadCount: state.unreadCount + (notification.read ? 0 : 1),
          }));
        },

        // 重置状态
        reset: () => {
          set({
            notifications: [],
            unreadCount: 0,
            isLoading: false,
            error: null,
          });
        },
      }),
      {
        name: 'notification-storage',
        partialize: (state) => ({
          notifications: state.notifications,
          unreadCount: state.unreadCount,
        }),
      }
    )
  )
); 